package cn.itcast.httpclient;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/*
 * 使用ResponseHandler来处理请求和响应
 */
public class ResponseHandlerTest {
    public static void main(String[] args) throws Exception {

         doGet();
//        doPost();
    }

    // 测试Get请求
    public static void doGet() throws ClientProtocolException, IOException {
        // 创建HttpGet请求，相当于在浏览器输入地址
        HttpGet httpGet = new HttpGet("http://www.baidu.com/");
        execute(httpGet);
    }

    // 测试POST请求
    private static void doPost() throws ClientProtocolException, IOException {

        // 创建http POST请求
        HttpPost httpPost = new HttpPost("https://www.oschina.net/");
        // 把自己伪装成浏览器。否则开源中国会拦截访问
        httpPost.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        execute(httpPost);
    }

    private static void execute(HttpRequestBase request) throws ClientProtocolException, IOException {
        // 创建Httpclient对象,相当于打开了浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 发起请求时，直接使用ResponseHandler，响应处理器。用户不需要关心链接的释放问题
        // 默认的响应处理器，会把结果处理为字符串
        String result = httpclient.execute(request, new BasicResponseHandler());
        System.out.println(result);
        // 关闭客户端
        httpclient.close();
    }
}
